package com.hertz.appr.service;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import net.htmlparser.jericho.Source;

import org.apache.log4j.Logger;

import com.hertz.appr.dao.IBaseDao;
import com.hertz.appr.http.HttpClientManager;
import com.hertz.appr.pojo.Mentions;
import com.hertz.appr.pojo.db.Message;
import com.hertz.appr.util.Configuration;
import com.hertz.appr.util.Constants;

public class MessageService {

	private Logger log = Logger.getLogger(MessageService.class);
	
	private IBaseDao<Message, Long> messageDao;
	
	public void save(Message msg){
		log.debug("save message : " + msg.toString());
		messageDao.save(msg);
	}
	
	public void update(Message msg){
		log.debug("update message : " + msg.toString());
		messageDao.update(msg);
	}
	
	/**
	 * 判断微博是否被删除
	 * 已删除则返回true
	 * 若出现异常，则认为微博存在，返回false
	 * @param msg
	 */
	public boolean checkMessageIsDelete(Message msg){
		log.debug(msg);
		log.info("check msg weather delete");
		boolean isDelete = false;
		if(msg.getProvider().equals(Configuration.QQ_PROVIDER)){
			String url = Constants.baseUrlQQ + "t/" + msg.getTid();
			log.debug("check url=" + url);
			try {
				String content = HttpClientManager.get(url);
				if(content == null){
					isDelete = true;
					log.debug("msg is delete");
				}else if(content.indexOf("您的页面暂时无法找到！") >= 0){
					isDelete = true;
					log.debug("msg is delete");
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		msg.setDeleteFlag(isDelete);
		update(msg);
		log.info("update msg deleteFlag=" + isDelete);
		return isDelete;
	}
	
	public Message getMsgById(Long mid){
		return messageDao.getById(mid);
	}
	
	public List<Message> getMessageByAid(Long aid,String provider){
		String hql = "from Message m where m.provider=? and m.actionId=? order by m.createTime asc";
		return messageDao.find(hql, provider,aid);
	}
	
//	public List<Message> getMessageBy

	public IBaseDao<Message, Long> getMessageDao() {
		return messageDao;
	}

	public void setMessageDao(IBaseDao<Message, Long> messageDao) {
		this.messageDao = messageDao;
	}
	
}
